﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Blazor.Templates;
using Microsoft.JSInterop;

namespace EasyXaf.BlazorTabbedMdi;

public partial class MdiMainWindowTemplateComponent : FrameTemplateComponentBase<MdiMainWindowTemplate>
{
    private bool IsFirstRenderCompleted { get; set; }

    private string DetailViewHeaderClass => FrameTemplate.View is DetailView ? "xaf-detail-view-header" : default;

    private string NavigateBackActionHeaderClass => FrameTemplate.NavigateBackActionControl.Visible ? "xaf-show-navigate-back-action" : default;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("xaf.initApplicationWindowTemplate");
            FrameTemplate.IsMobile = await JSRuntime.InvokeAsync<bool>("xaf.device.isMobile");
            FrameTemplate.StateChanged += (s, e) => StateHasChanged();
            IsFirstRenderCompleted = true;
            StateHasChanged();
        }

        FrameTemplate.DisposeableViews.ForEach(v => v.Dispose());
        FrameTemplate.DisposeableViews.Clear();

        FrameTemplate.DisposeableWindows.ForEach(v => v.Dispose());
        FrameTemplate.DisposeableWindows.Clear();
    }

    protected override async Task InvokeAfterViewChangedJS()
    {
        await JSRuntime.InvokeVoidAsync("xaf.closeSideBarIfMobile");
        await base.InvokeAfterViewChangedJS();
    }
}
